/**
 * 
 */
package jmine.tec.web.wicket.upperCase;

import org.apache.wicket.Component;
import org.apache.wicket.application.IComponentOnBeforeRenderListener;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IComponentInheritedModel;
import org.apache.wicket.model.IModel;

/**
 * {@link IComponentOnBeforeRenderListener} to replace models on {@link TextField}
 * 
 * @author takeshi
 */
public final class UpperCaseBeforeRenderListener implements IComponentOnBeforeRenderListener {

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public void onBeforeRender(Component component) {
        if (component instanceof FormComponent && shouldReplaceModel(component)) {
            FormComponent<?> fc = (FormComponent<?>) component;
            IModel model = fc.getModel();
            if (!(model instanceof UpperCaseModelWrapper<?>)) {
                fc.setModel(new UpperCaseModelWrapper(fc.getModel()));
            }
        }
        // Search parents for IComponentInheritedModel
        for (Component current = component.getParent(); current != null; current = current.getParent()) {
            IModel<?> foundModel = current.getDefaultModel();
            if (foundModel != null && !(foundModel instanceof UpperCaseInheritedModel<?>) && foundModel instanceof IComponentInheritedModel) {
                current.setDefaultModel(new UpperCaseInheritedModel((IComponentInheritedModel) foundModel));
                break;
            }
        }
    }

    /**
     * Checks whether the component should have its model changed to an {@link UpperCaseModelWrapper}. As of now, only {@link TextField} and
     * its subclasses require that.
     * 
     * @param component {@link Component}
     * @return boolean
     */
    public static boolean shouldReplaceModel(Component component) {
        return component instanceof TextField<?> && !(component instanceof NoUpperCaseTextField);
    }
}